package launcher;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class Main {

	private static HashMap<Character, Integer> LETTERVALUES = new HashMap<Character, Integer>();
	private static List<Word> DICTONARY = new ArrayList<Word>();

	public static void main(String[] argv) {

		String dicoFile = "enable1.txt";
		String letterFile = "lettervalues";
		String handFile = "hand";
		Word hand;

		// lecture du fichier texte
		try {
			InputStream ips = new FileInputStream(dicoFile);
			InputStreamReader ipsr = new InputStreamReader(ips);
			BufferedReader br = new BufferedReader(ipsr);
			String line;
			while ((line = br.readLine()) != null) {
				DICTONARY.add(new Word(line));
			}
			br.close();

			ips = new FileInputStream(letterFile);
			ipsr = new InputStreamReader(ips);
			br = new BufferedReader(ipsr);

			while ((line = br.readLine()) != null) {
				LETTERVALUES.put(line.charAt(0),
						Integer.parseInt(line.substring(1)));
			}
			br.close();
		} catch (Exception e) {
			System.out.println(e.toString());
		}

		try {
			InputStream ips = new FileInputStream(handFile);
			InputStreamReader ipsr = new InputStreamReader(ips);
			BufferedReader br = new BufferedReader(ipsr);

			ipsr = new InputStreamReader(ips);
			br = new BufferedReader(ipsr);
			hand = new Word(br.readLine());
			br.close();
		} catch (Exception e) {
			System.out.println(e.toString());
		}
		Word blip = new Word("aah");
		List<Word> blop = filterList(blip.getLetterOccur(), DICTONARY);
		
		for (Word word : blop) {
			System.out.println(word.getStrMot());

		}

	}

	public static List<Word> filterList(HashMap<Integer, Integer> hand,
			List<Word> list) {
		List<Word> filtredList = new ArrayList<Word>();
		int handSize = hand.size();

		for (Word word : list) {
			//System.out.println(handSize + " / " + wordLetters.size());
			if (handSize >=  word.getLetterOccur().size()) {
				boolean isPresent = true;
				Iterator<Entry<Integer, Integer>> it =  word.getLetterOccur().entrySet()
						.iterator();

				while (it.hasNext() && isPresent) {

					@SuppressWarnings("rawtypes")
					Map.Entry pairs = (Map.Entry) it.next();
					if (!hand.containsKey(pairs.getKey())
							|| !( word.getLetterOccur().get(pairs.getKey()) <= hand
									.get(pairs.getKey()))) {
						isPresent = false;
					}

					it.remove();
				}
				if (isPresent) {
					filtredList.add(word);
				}

			}
		}

		return filtredList;
	}

	public static HashMap<Character, Integer> getLetterValues() {
		return LETTERVALUES;
	}

}
